package main

import (
	"context"
	"fmt"
	"github.com/micro/go-micro"
	"github.com/micro/go-micro/client"
	"github.com/micro/go-micro/client/grpc"
	transport "github.com/micro/go-micro/transport/grpc"
	"github.com/micro/go-plugins/registry/etcdv3"
	proto "micro-learning/proto/greeter"
	"time"
)

func main() {
	// Create a new service. Optionally include some options here.
	service := micro.NewService(
		micro.Client(grpc.NewClient(client.Registry(etcdv3.NewRegistry()),
			client.Transport(transport.NewTransport()),

			// 每次调用失败时候(retry)，会调用方法，延时重试。
			// 每次发送前都会调用该方法，有时候第一次发送需要延时。
			client.Backoff(func(ctx context.Context, req client.Request, attempts int) (duration time.Duration, e error) {
				fmt.Println(ctx, req, attempts)
				return duration.Round(time.Duration(12000000)), nil
			}),

			client.Retries(3),
			client.PoolSize(1024),
			client.DialTimeout(2*time.Second),
			client.RequestTimeout(2*time.Second),

			// retry 函数，重试将被调用
			client.Retry(func(ctx context.Context, req client.Request, retryCount int, err error) (b bool, e error) {
				fmt.Println("return false 或者 error 非空 , 将不会再次retry ", retryCount, req, ctx)
				return true, e
			}),
		)))
	service.Init()

	// Create new greeter client
	greeter := proto.NewGreeterService("greeter", service.Client())

	// Call the greeter
	rsp, err := greeter.Hello(context.TODO(), &proto.HelloRequest{Name: "John"})
	if err != nil {
		fmt.Println(err)
	}

	// Print response
	fmt.Println(rsp.Greeting)
}
